import React, { useState, useEffect } from 'react';

import {
  Box,
  Paper,
  Stack,
  Button,
  Typography,
  Card,
  CardContent,
  Chip,
  IconButton,
  Tooltip,
  Alert,
  Divider,
  Grid,
} from '@mui/material';
import { DataGrid, GridColDef } from '@mui/x-data-grid';
import { isDeepEqual } from '@mui/x-data-grid/internals';
import { Iconify } from '../../../components/iconify';
import { DashboardContent } from 'src/layouts/dashboard';

import { rowAddIndex } from '../../../utils/data';
import { getRows, cashBookTableHead } from '../detail-data';
import { getCashList, updateBatch } from '../../../api/cash-book';

import type { RowsInterface } from '../detail-data';

// ----------------------------------------------------------------------
export function ProductView() {
  const [loading, setLoading] = useState<boolean>(true);
  const [paginationModel, setPaginationModel] = useState({ page: 0, pageSize: 50, totalCount: 0 });
  const [cashBookDetailsList, setCashBookDetailsList] = useState<RowsInterface[]>([]);
  const [updateList, setUpdateList] = useState<RowsInterface[]>([]);
  const [visiable, setVisiable] = useState(false);

  // 获取流水数据
  const getCashBookDetails = () => {
    setLoading(true);
    getCashList(paginationModel.page + 1, paginationModel.pageSize)
      .then((r) => {
        const rows = rowAddIndex(getRows(r));
        setCashBookDetailsList(rows);
        setPaginationModel((prev) => ({
          ...prev,
          totalCount: r.total,
        }));
      })
      .finally(() => {
        setLoading(false);
      });
  };

  const handlePaginationModelChange = (newPaginationModel: any) => {
    setPaginationModel(newPaginationModel);
  };

  useEffect(() => {
    getCashBookDetails();
  }, [paginationModel.page, paginationModel.pageSize]);

  const processRowUpdate = (newRow: RowsInterface, oldRow: RowsInterface) => {
    if (!isDeepEqual(newRow, oldRow)) {
      setUpdateList((prevItems) => {
        const newList = new Map();
        prevItems.concat(newRow).forEach((item) => newList.set(item.id, item));
        return Array.from(newList.values());
      });
      setVisiable(true);
    }
    return newRow;
  };

  const handleRowUpdateError = (error: any) => {
    console.log(error);
  };

  const update = () => {
    updateBatch(updateList).then((res) => {
      setVisiable(false);
      setUpdateList([]);
      getCashBookDetails();
    });
  };

  const cancel = () => {
    setUpdateList([]);
    setVisiable(false);
    getCashBookDetails();
  };

  // 计算统计信息
  const calculateStats = () => {
    if (!cashBookDetailsList.length) return { totalAmount: 0, totalCount: 0 };
    
    const totalAmount = cashBookDetailsList.reduce((sum, row) => {
      return sum + (Number(row.amount) || 0);
    }, 0);
    
    return {
      totalAmount: totalAmount.toFixed(2),
      totalCount: cashBookDetailsList.length
    };
  };

  const stats = calculateStats();

  // 优化的列定义 - 自适应宽度
  const columns: GridColDef[] = [
    {
      field: 'index',
      headerName: '序号',
      width: 80,
      flex: 0,
      headerAlign: 'center',
      align: 'center',
      renderCell: (params) => (
        <Tooltip 
          title={`序号: ${params.value}`}
          placement="right-start"
          arrow
          enterDelay={300}
          leaveDelay={200}
          PopperProps={{
            sx: {
              zIndex: 9999,
              '& .MuiTooltip-tooltip': {
                backgroundColor: 'rgba(0, 0, 0, 0.87)',
                color: 'white',
                fontSize: '12px',
                padding: '8px 12px',
              },
              '& .MuiTooltip-arrow': {
                color: 'rgba(0, 0, 0, 0.87)',
              },
            },
          }}
        >
          <Chip 
            label={params.value} 
            size="small" 
            color="primary" 
            variant="outlined"
            sx={{
              cursor: 'pointer',
              '&:hover': {
                backgroundColor: 'primary.main',
                color: 'white',
                transform: 'scale(1.05)',
                transition: 'all 0.2s ease-in-out',
              },
            }}
          />
        </Tooltip>
      ),
    },
    {
      field: 'consumerDate',
      headerName: '消费日期',
      width: 140,
      flex: 1,
      editable: true,
      headerAlign: 'center',
      align: 'center',
      renderCell: (params) => (
        <Typography variant="body2" color="text.secondary" sx={{ textAlign: 'center' }}>
          {params.value}
        </Typography>
      ),
    },
    {
      field: 'amount',
      headerName: '消费金额',
      width: 140,
      flex: 1,
      editable: true,
      headerAlign: 'center',
      align: 'center',
      renderCell: (params) => {
        const value = Number(params.value) || 0;
        const isPositive = value >= 0;
        return (
          <Typography
            variant="body2"
            color={isPositive ? 'success.main' : 'error.main'}
            sx={{ fontWeight: 'bold', textAlign: 'center' }}
          >
            {isPositive ? '+' : ''}{value.toFixed(2)}
          </Typography>
        );
      },
    },
    {
      field: 'payUserName',
      headerName: '支付人',
      width: 120,
      flex: 1,
      editable: true,
      headerAlign: 'center',
      align: 'center',
      renderCell: (params) => (
        <Chip 
          label={params.value || '-'} 
          size="small" 
          color="info" 
          variant="outlined"
          sx={{ width: '100%', justifyContent: 'center' }}
        />
      ),
    },
    {
      field: 'forUserName',
      headerName: '受益人',
      width: 120,
      flex: 1,
      editable: true,
      headerAlign: 'center',
      align: 'center',
      renderCell: (params) => (
        <Chip 
          label={params.value || '-'} 
          size="small" 
          color="success" 
          variant="outlined"
          sx={{ width: '100%', justifyContent: 'center' }}
        />
      ),
    },
    {
      field: 'payWay',
      headerName: '支付方式',
      width: 120,
      flex: 1,
      editable: true,
      headerAlign: 'center',
      align: 'center',
      renderCell: (params) => (
        <Chip 
          label={params.value || '-'} 
          size="small" 
          color="warning" 
          variant="outlined"
          sx={{ width: '100%', justifyContent: 'center' }}
        />
      ),
    },
    {
      field: 'payPlat',
      headerName: '交易对方',
      width: 140,
      flex: 1,
      editable: true,
      headerAlign: 'center',
      align: 'center',
      renderCell: (params) => (
        <Chip 
          label={params.value || '-'} 
          size="small" 
          color="secondary" 
          variant="outlined"
          sx={{ width: '100%', justifyContent: 'center' }}
        />
      ),
    },
    {
      field: 'remark',
      headerName: '备注',
      width: 200,
      flex: 1,
      editable: true,
      headerAlign: 'center',
      align: 'center',
      renderCell: (params) => (
        <Typography variant="body2" color="text.secondary" sx={{ textAlign: 'center' }}>
          {params.value || '-'}
        </Typography>
      ),
    },
  ];

  return (
    <DashboardContent maxWidth="xl">
      <Box>
        {/* 页面标题 */}
        <Typography variant="h4" sx={{ mb: 2, fontWeight: 'bold' }}>
          流水管理
        </Typography>

        {/* 统计卡片 */}
        <Grid container spacing={2} sx={{ mb: 2 }}>
          <Grid item xs={12} md={4}>
            <Card sx={{ 
              background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
              color: 'white'
            }}>
              <CardContent>
                <Box display="flex" alignItems="center" justifyContent="space-between">
                  <Box>
                    <Typography variant="h6" sx={{ mb: 1, opacity: 0.8 }}>
                      总消费金额
                    </Typography>
                    <Typography variant="h4" sx={{ fontWeight: 'bold' }}>
                      ¥{stats.totalAmount}
                    </Typography>
                  </Box>
                  <Iconify icon="eva:trending-up-fill" sx={{ fontSize: 48, opacity: 0.8 }} />
                </Box>
              </CardContent>
            </Card>
          </Grid>
          
          <Grid item xs={12} md={4}>
            <Card sx={{ 
              background: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
              color: 'white'
            }}>
              <CardContent>
                <Box display="flex" alignItems="center" justifyContent="space-between">
                  <Box>
                    <Typography variant="h6" sx={{ mb: 1, opacity: 0.8 }}>
                      总记录数
                    </Typography>
                    <Typography variant="h4" sx={{ fontWeight: 'bold' }}>
                      {stats.totalCount}
                    </Typography>
                  </Box>
                  <Iconify icon="eva:file-text-fill" sx={{ fontSize: 48, opacity: 0.8 }} />
                </Box>
              </CardContent>
            </Card>
          </Grid>
          
          <Grid item xs={12} md={4}>
            <Card sx={{ 
              background: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
              color: 'white'
            }}>
              <CardContent>
                <Box display="flex" alignItems="center" justifyContent="space-between">
                  <Box>
                    <Typography variant="h6" sx={{ mb: 1, opacity: 0.8 }}>
                      当前页数
                    </Typography>
                    <Typography variant="h4" sx={{ fontWeight: 'bold' }}>
                      {paginationModel.page + 1}
                    </Typography>
                  </Box>
                  <Iconify icon="eva:layers-fill" sx={{ fontSize: 48, opacity: 0.8 }} />
                </Box>
              </CardContent>
            </Card>
          </Grid>
        </Grid>

        {visiable && (
          <Alert 
            severity="info" 
            sx={{ mb: 2 }}
            action={
              <Stack direction="row" spacing={1}>
                <Button 
                  color="primary" 
                  variant="contained" 
                  size="small"
                  onClick={update}
                  startIcon={<Iconify icon="eva:checkmark-fill" />}
                >
                  保存更改
                </Button>
                <Button 
                  color="error" 
                  variant="outlined" 
                  size="small"
                  onClick={cancel}
                  startIcon={<Iconify icon="eva:close-fill" />}
                >
                  取消
                </Button>
              </Stack>
            }
          >
            您有未保存的更改，请选择保存或取消
          </Alert>
        )}

        {/* 数据表格 */}
        <Card sx={{ height: 'calc(100vh - 200px)', minHeight: 800 }}>
          <CardContent sx={{ p: 0, height: '100%' }}>
            <Box sx={{ height: '100%', width: '100%' }}>
              <DataGrid
                rows={cashBookDetailsList}
                columns={columns}
                loading={loading}
                pagination
                paginationModel={paginationModel}
                pageSizeOptions={[25, 50, 100]}
                rowCount={paginationModel.totalCount || 0}
                paginationMode="server"
                processRowUpdate={processRowUpdate}
                getRowId={(row) => row.id || `row-${row.index || Math.random()}`}
                sx={{
                  border: 'none',
                  height: '100%',
                  width: '100%',
                  // 全局弹窗层级修复 - 确保所有弹窗都在最上层
                  '& *': {
                    '&[data-popper-placement]': {
                      zIndex: '99999 !important',
                    },
                    '&[role="tooltip"]': {
                      zIndex: '99999 !important',
                    },
                    '&[role="menu"]': {
                      zIndex: '99999 !important',
                    },
                    '&[role="dialog"]': {
                      zIndex: '99999 !important',
                    },
                  },
                  '& .MuiDataGrid-cell': {
                    borderBottom: '1px solid #f0f0f0',
                    zIndex: 1,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    padding: '8px 4px',
                  },
                  '& .MuiDataGrid-columnHeaders': {
                    backgroundColor: '#fafafa',
                    borderBottom: '2px solid #e0e0e0',
                  },
                  '& .MuiDataGrid-columnHeader': {
                    backgroundColor: '#fafafa',
                    borderBottom: '2px solid #e0e0e0',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    padding: '12px 4px',
                  },
                  '& .MuiDataGrid-row:hover': {
                    backgroundColor: '#f5f5f5',
                  },
                  '& .MuiDataGrid-row': {
                    zIndex: 1,
                    minHeight: '48px',
                  },
                  // 修复弹窗和分页器被遮挡的问题
                  '& .MuiDataGrid-panel': {
                    zIndex: 99999,
                  },
                  '& .MuiDataGrid-menu': {
                    zIndex: 99999,
                  },
                  '& .MuiDataGrid-pagination': {
                    zIndex: 1000,
                  },
                  '& .MuiDataGrid-footerContainer': {
                    zIndex: 1000,
                  },
                  '& .MuiDataGrid-virtualScroller': {
                    zIndex: 1,
                  },
                  '& .MuiDataGrid-columnsContainer': {
                    zIndex: 1000,
                  },
                  // 确保Chip组件的弹窗不被遮挡
                  '& .MuiChip-root': {
                    position: 'relative',
                    zIndex: 100,
                    width: '100%',
                    justifyContent: 'center',
                  },
                  '& .MuiChip-deleteIcon': {
                    position: 'relative',
                    zIndex: 101,
                  },
                  // 修复Tooltip和Menu的层级
                  '& .MuiTooltip-popper': {
                    zIndex: 99999,
                  },
                  '& .MuiMenu-root': {
                    zIndex: 99999,
                  },
                  '& .MuiPopover-root': {
                    zIndex: 99999,
                  },
                  // 修复列排序弹窗被遮挡的问题
                  '& .MuiDataGrid-columnHeaderSortIcon': {
                    zIndex: 1000,
                  },
                  '& .MuiDataGrid-columnHeaderTitle': {
                    zIndex: 1000,
                  },
                  '& .MuiDataGrid-columnHeaderDraggableContainer': {
                    zIndex: 1000,
                  },
                  // 确保所有弹出层都有足够高的z-index
                  '& .MuiPopper-root': {
                    zIndex: 99999,
                  },
                  '& .MuiPaper-root': {
                    zIndex: 99999,
                  },
                  // 修复列菜单弹窗
                  '& .MuiDataGrid-columnMenu': {
                    zIndex: 99999,
                  },
                  '& .MuiDataGrid-columnMenuList': {
                    zIndex: 99999,
                  },
                  '& .MuiDataGrid-columnMenuPaper': {
                    zIndex: 99999,
                  },
                  // 修复筛选弹窗
                  '& .MuiDataGrid-filterForm': {
                    zIndex: 99999,
                  },
                  '& .MuiDataGrid-filterPanel': {
                    zIndex: 99999,
                  },
                  // 修复所有可能的弹窗组件
                  '& .MuiAutocomplete-popper': {
                    zIndex: 99999,
                  },
                  '& .MuiSelect-popper': {
                    zIndex: 99999,
                  },
                  '& .MuiMenu-paper': {
                    zIndex: 99999,
                  },
                  '& .MuiPopover-paper': {
                    zIndex: 99999,
                  },
                  '& .MuiTooltip-tooltip': {
                    zIndex: 99999,
                  },
                  // 确保DataGrid内部的所有弹窗都在最上层
                  '& [data-popper-placement]': {
                    zIndex: 99999,
                  },
                  '& [role="tooltip"]': {
                    zIndex: 99999,
                  },
                  '& [role="menu"]': {
                    zIndex: 99999,
                  },
                  '& [role="dialog"]': {
                    zIndex: 99999,
                  },
                }}
                onPaginationModelChange={handlePaginationModelChange}
                onProcessRowUpdateError={handleRowUpdateError}
                initialState={{
                  pagination: {
                    paginationModel: {
                      pageSize: 50,
                    },
                  },
                }}
              />
            </Box>
          </CardContent>
        </Card>
      </Box>
    </DashboardContent>
  );
}
